package com.harisucici.app

import android.os.Bundle
import android.view.View
import androidx.datastore.DataStore
import androidx.datastore.preferences.*
import androidx.lifecycle.lifecycleScope
import com.harisucici.app.databinding.ActivityThirdBinding
import com.harisucici.jetpackbase.base.HBaseActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.io.IOException
import java.util.*

class ThirdActivity : HBaseActivity<ActivityThirdBinding, MainModel>() {

    val PREFERENCE_NAME = "DataStore"
    val KEY_BYTE_CODE = preferencesKey<String>("HelloWorld")
    lateinit var dataStore: DataStore<Preferences>

    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_third
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }


    override fun initParam() {
        super.initParam()
        dataStore = createDataStore(name = PREFERENCE_NAME)
    }

    override fun initData(v: View?) {
        super.initData(v)


        binding!!.setButton.setOnClickListener {
            val time = System.currentTimeMillis()
            lifecycleScope.launch(Dispatchers.IO) {
                for (i in 0..4999) {
                    onSave("Hello World$i")
                }
                viewModel!!.text.set(String.format(Locale.getDefault(), "运行时间：%d毫秒", System.currentTimeMillis() - time))
            }
        }

        binding!!.getButton.setOnClickListener {
            lifecycleScope.launch(Dispatchers.IO) {
                viewModel!!.text.set(onRead())

            }
        }
    }


    suspend fun onSave(value: String) {
        var preKey = KEY_BYTE_CODE
        dataStore.edit { mutablePreferences ->
            mutablePreferences[preKey] = value
        }
    }

    suspend fun onRead(): String {
        var preKey = KEY_BYTE_CODE
        var value = dataStore.data.map { preferences ->
            preferences[preKey] ?: ""
        }
        return value.first()
    }


    fun readData(key: Preferences.Key<String>) =
            dataStore.data
                    .catch {
                        // 当读取数据遇到错误时，如果是 `IOException` 异常，发送一个 emptyPreferences 来重新使用
                        // 但是如果是其他的异常，最好将它抛出去，不要隐藏问题
                        if (it is IOException) {
                            it.printStackTrace()
                            emit(emptyPreferences())
                        } else {
                            throw it
                        }
                    }.map { preferences ->
                        preferences[key] ?: false
                    }

    suspend fun saveData(content: String) {
        dataStore.edit { settings ->
            val string = settings[KEY_BYTE_CODE] ?: ""
            settings[KEY_BYTE_CODE] = content
        }
    }


}
